package com.ruoyi.web.util;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class WordUtils {


    public static void fillTemplate(InputStream templateInputStream, OutputStream outputStream, Map<String, Object> dataMap) throws IOException, XmlException {
        try (XWPFDocument document = new XWPFDocument(templateInputStream)) {

            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    if (text != null) {
                        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                            text = text.replace("${" + entry.getKey() + "}", String.valueOf(entry.getValue() != null ? entry.getValue() : ""));
                        }
                        run.setText(text, 0);
                    }
                }
            }

            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            for (XWPFRun run : paragraph.getRuns()) {
                                String text = run.getText(0);
                                if (text != null) {
                                    for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                                        text = text.replace("${" + entry.getKey() + "}", String.valueOf(entry.getValue() != null ? entry.getValue() : ""));
                                    }
                                    run.setText(text, 0);
                                }
                            }
                        }
                    }
                }
            }

            document.write(outputStream);
        }
    }
}
